var app = getApp();
var util = require('../../../utils/util');

Page({

  data: {
    categoryTitle: '',
    movies: [],
    requestUrl: '',
    totalCount: 0,
    isEmpty: false
  },
  onLoad: function(options) {
    // 获取url地址传递过来的参数category
    var category = options.category;
    this.setData({
      categoryTitle: category
    });
    var dataUrl = '';
    switch (category) {
      case '正在热映':
        dataUrl = app.globalData.doubanbase +
          '/v2/movie/in_theaters';
        break;
      case '即将上映':
        dataUrl = app.globalData.doubanbase +
          '/v2/movie/coming_soon';
        break;
      case '豆瓣Top250':
        dataUrl = app.globalData.doubanbase +
          '/v2/movie/top250';
        break;
    }

    this.data.requestUrl = dataUrl;
    util.http(dataUrl, this.processDoubanData);
  },

  // 滑动加载电影
  onScrollLower: function (event) {
    var nextUrl = this.data.requestUrl +
      '?start=' + this.data.totalCount + '&count=20';
    util.http(nextUrl, this.processDoubanData);
    // 显示加载的loading
    wx.showNavigationBarLoading();
  },

  onPullDownRefresh: function(event) {
    var refreshUrl = this.data.requestUrl + 
    '?start=0&count=20';
    // 滞空
    this.data.movies = [];
    this.data.isEmpty = true;
    util.http(refreshUrl, this.processDoubanData);
    wx.showNavigationBarLoading();
  },

  processDoubanData: function(moviesDouban) {
    // 定义数组，存储数据
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        // 如果标题大于等于6位，则截取6位，后面用...表示
        title = title.substring(0, 6) + '...';
      }
      // 定义temp对象，存储电影数据
      var temp = {
        movieId: subject.id,
        coverageUrl: subject.images.large,
        title: title,
        average: subject.rating.average,
        stars: util.convertToStarArray(subject.rating.stars)
      };
      movies.push(temp);
    }
    var totalMovies = {};
    // 如果要绑定新加载的数据，那么需要和旧有的数据绑定在一起
    if (!this.data.isEmpty) {
      totalMovies = this.data.movies.concat(movies);
    } else {
      totalMovies = movies;
      this.data.isEmpty = false;
    }
    this.setData({
      movies: totalMovies
    });

    this.data.totalCount += 20;

    // 隐藏加载的loading
    wx.hideNavigationBarLoading();
    // 停止下拉刷新
    wx.stopPullDownRefresh();
  },

  // 生命周期函数，页面渲染完成后
  // 动态设置导航栏标题
  onReady: function(event) {
    wx.setNavigationBarTitle({
      title: this.data.categoryTitle
    });
  }

})